//RegisterServlet.java
package com.ylaihui.web;

import com.ylaihui.pojo.User;
import com.ylaihui.service.UserService;
import com.ylaihui.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        // 校验验证码， 先校验是否 为 123abc
        if("123abc".equalsIgnoreCase(code)) {
            // 检查用户名是否存在
            boolean b = userService.existsUsername(username);
            if (b == true) {
                // 用户名已经存在,回显信息
                req.setAttribute("msg", "用户名已经存在");
                req.setAttribute("username", username);
                req.setAttribute("email", email);

                // 用户名已经存在
                System.out.println("用户名不可用"+ username);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                userService.registUser(new User(null, username,password,email));
                // 注册成功， 请求转发到 注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else {
            // 验证码错误，回显信息
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", username);
            req.setAttribute("email", email);

            // 验证码输入错误，请求转发到 注册页面
            System.out.println("验证码错误 " + code);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }
}
